<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
      <el-form-item label="想定名称" prop="schemeName">
        <el-input
          v-model="queryParams.schemeName"
          placeholder="请输入想定名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="想定制作时间" prop="schemeCreateTime">
        <el-date-picker
          v-model="schemeCreateQueryTime"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          placeholder="请输入想定制作时间"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 240px"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="想定制作人" prop="schemeCreater">
        <el-input
          v-model="queryParams.schemeCreater"
          placeholder="请输入想定制作人"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="small"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:user:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button v-hasPermi="['system:user:remove']"
                   type="danger"
                   plain
                   icon="el-icon-delete"
                   size="mini"
                   :disabled="multiple"
                   @click="handleDelete">删除</el-button>
      </el-col> -->
      <!-- <right-toolbar
        :show-search.sync="showSearch"
        :columns="columns"
        @queryTable="getList"
      /> -->
    </el-row>

    <el-table
      v-loading="loading"
      :data="schemeList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        label="想定名称"
        align="center"
        prop="schemeName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="想定制作时间"
        align="center"
        prop="schemeCreateTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.schemeCreateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="想定制作人"
        align="center"
        prop="schemeCreater"
        width="180"
      />
      <el-table-column
        label="想定开始时间"
        align="center"
        prop="schemeStartTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.schemeStartTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="想定结束时间"
        align="center"
        prop="schemeEndTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.schemeEndTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.status == "1" ? "使用中" : "未使用" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['system:dict:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            :disabled="scope.row.status == '1'"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            v-hasPermi="['system:dict:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="700px"
      append-to-body
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <template v-if="showState">
          <el-form-item label="想定名称" prop="schemeName">
            <el-input
              v-model="form.schemeName"
              style="width: 80%"
              placeholder="请输入想定名称"
            />
          </el-form-item>
          <el-form-item label="想定制作时间" prop="schemeCreateTime">
            <div class="el-datetime-width">
              <el-date-picker
                v-model="form.schemeCreateTime"
                type="datetime"
                style="width: 80%"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择想定制作时间"
              />
            </div>
          </el-form-item>
          <el-form-item label="想定制作人" prop="schemeCreater">
            <el-input
              v-model="form.schemeCreater"
              style="width: 80%"
              placeholder="请输入想定制作人"
            />
          </el-form-item>
          <el-form-item label="想定开始时间" prop="schemeStartTime">
            <div class="el-datetime-width">
              <el-date-picker
                v-model="form.schemeStartTime"
                style="width: 80%"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择想定开始时间"
              />
            </div>
          </el-form-item>
          <el-form-item label="想定结束时间" prop="schemeEndTime">
            <div class="el-datetime-width">
              <el-date-picker
                v-model="form.schemeEndTime"
                style="width: 80%"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择想定结束时间"
              />
            </div>
          </el-form-item>
          <el-form-item label="仿真步长" prop="emulateStep">
            <el-input
              v-model="form.emulateStep"
              style="width: 80%"
              placeholder="请输入仿真步长"
              @change="emulateStepFormatter"
            />
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-input
              v-model="form.type"
              style="width: 80%"
              placeholder="请输入类型"
            />
          </el-form-item>
          <el-form-item label="制作单位" prop="schemeCreateCompany">
            <el-input
              v-model="form.schemeCreateCompany"
              style="width: 80%"
              placeholder="请输入制作单位"
            />
          </el-form-item>
          <el-form-item label="想定描述" prop="description">
            <el-input
              v-model="form.description"
              style="width: 80%"
              placeholder="请输入仿真步长"
            />
          </el-form-item>
        </template>
        <el-form-item v-else label="想定方案上传" prop="emulateUpload">
          <fileUpload
            ref="upload"
            :limit="1"
            :file-size="500"
            :file-type="['scn']"
            :value="form.schemeUrl"
            @input="getSchemeFileUrl"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          v-show="showState"
          type="primary"
          @click="reUpload"
          size="small"
          >重新上传</el-button
        >
        <el-button
          v-show="showState"
          type="primary"
          @click="submitForm"
          size="small"
          >确 定</el-button
        >
        <el-button @click="cancel" size="small" plain>取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  listScheme,
  updateScheme,
  addScheme,
  delScheme,
  getScheme,
  parseScheme,
} from "@/api/resource/scheme";
import { watch } from "vue";
export default {
  name: "Scheme",
  data() {
    // 仿真步长校验
    var checkEmulateStep = (rule, value, callback) => {
      if (!value) {
        callback(new Error("仿真步长不能为空"));
      }
      setTimeout(() => {
        if (value <= 0) {
          callback(new Error("仿真步长值需大于零"));
        } else {
          callback();
        }
      }, 1000);
    };
    // 想定开始时间与结束时间的校验
    var checkSchemeTime = (rule, value, callback) => {
      if (value <= this.form.schemeStartTime) {
        callback(new Error("想定结束时间不能小于想定开始时间"));
      } else {
        callback();
      }
    };
    return {
      // 遮罩层
      loading: true,
      // 想定数据列表
      schemeList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        schemeName: undefined,
        schemeCreateTime: undefined,
        schemeCreater: undefined,
      },
      total: 0,
      schemeCreateQueryTime: undefined,
      // 表单参数
      form: {
        schemeName: undefined,
        schemeCreateTime: undefined,
        schemeStartTime: undefined,
        schemeEndTime: undefined,
        schemeUrl: undefined,
        emulateStep: "1.00",
        type: undefined,
        description: undefined,
        schemeCreateCompany: undefined,
        id: undefined,
      },
      // 表单校验
      rules: {
        schemeName: [
          { required: true, message: "想定名称不能为空", trigger: "blur" },
        ],
        schemeCreater: [
          { required: true, message: "想定制作人不能为空", trigger: "blur" },
        ],
        schemeCreateTime: [
          { required: true, message: "想定制作时间不能为空", trigger: "blur" },
        ],
        schemeStartTime: [
          { required: true, message: "想定开始时间不能为空", trigger: "blur" },
        ],
        schemeEndTime: [
          { required: true, message: "想定结束时间不能为空", trigger: "blur" },
          { validator: checkSchemeTime, trigger: "blur" },
        ],
        emulateStep: [
          { required: true, message: "仿真步长不能为空", trigger: "blur" },
          { pattern: /^(-?\d+)(\.\d+)?$/, message: "只能输入数字" },
          { validator: checkEmulateStep, trigger: "blur" },
        ],
      },
      // 是否显示想定新增，编辑想定方案弹窗
      open: false,
      // 新增，编辑想定方案弹窗title
      title: "",
      //是否显示想定表单内容，与想定上传组件显示状态互斥
      showState: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询想定列表 */
    getList() {
      this.loading = true;
      listScheme(
        this.addDateRange(
          this.queryParams,
          this.schemeCreateQueryTime,
          "SchemeCreateTime"
        )
      ).then((response) => {
        this.schemeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        schemeName: undefined,
        schemeCreateTime: undefined,
        schemeStartTime: undefined,
        schemeEndTime: undefined,
        schemeUrl: undefined,
        emulateStep: "1.00",
        type: undefined,
        description: undefined,
        schemeCreateCompany: undefined,
        id: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增想定方案操作 */
    handleAdd() {
      this.open = true;
      this.title = "新增想定方案";
      this.showState = false;
      this.$nextTick(() => {
        this.$refs.upload.handleDelete(0);
      });
      // this.resetForm('form')
      // this.form = {
      //   schemeName: undefined,
      //   schemeCreateTime: undefined,
      //   schemeStartTime: undefined,
      //   schemeEndTime: undefined,
      //   schemeUrl: '',
      //   emulateStep: '1.00',
      //   type: undefined,
      //   description: undefined,
      //   schemeCreateCompany:undefined
      // }
      this.reset();
    },
    /** 删除想定方案 */
    handleDelete(row) {
      const schemeId = row.schemeId;
      this.$modal
        .confirm("是否确认删除选中的方案么？")
        .then(function () {
          return delScheme(schemeId);
        })
        .then(() => {
          this.handleQuery();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 修改想定方案操作 */
    handleUpdate(row) {
      this.showState = true;
      this.resetForm("form");
      const schemeId = row.schemeId;
      getScheme(schemeId).then((response) => {
        this.form = response.data;
        this.emulateStepFormatter(response.data.emulateStep);
        this.open = true;
        this.title = "修改想定方案";
        this.$nextTick(() => {
          if (response.data.fileList) {
            let arr = [];
            arr.push(response.data.fileList);
            this.$refs.upload.fileList = arr;
            this.form.schemeUrl = arr[0].fileId;
          }
        });
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (
            this.form.schemeId !== undefined &&
            this.form.schemeId !== null &&
            this.form.schemeId !== ""
          ) {
            updateScheme(this.form).then((response) => {
              if (response.code == 200) {
                this.$modal.msgSuccess("修改成功");
                this.handleClose();
                this.getList();
              } else {
                this.$message.error(response.msg);
              }
            });
          } else {
            addScheme(this.form).then((response) => {
              if (response.code == 200) {
                this.$modal.msgSuccess("新增成功");
                this.resetForm("form");
                this.handleClose();
                this.getList();
              } else {
                this.$message.error(response.msg);
              }
            });
          }
        }
      });
    },
    // 表单取消按钮
    cancel() {
      this.open = false;
      this.getList();
      this.resetScheme();
    },

    // 表单重置
    resetScheme() {
      this.form = {};
      this.resetForm("form");
    },
    // 获取想定方案存储url
    getSchemeFileUrl(fileList) {
      if (fileList.length > 0) {
        this.form.schemeUrl = fileList[0].fileId;
        parseScheme(fileList[0].fileId).then((response) => {
          if (response.code == 200) {
            this.form = response.data;
            // 跳转表单
            this.showState = true;
          } else {
            this.$message.error(response.msg);
          }
        });
      }
    },
    handleClose() {
      this.open = false;
      if (this.$refs.upload) {
        this.$refs.upload.fileList = [];
      }
    },
    // 格式化步长
    emulateStepFormatter(x) {
      if (x.toString().indexOf(".") > -1) {
        this.form.emulateStep = (Math.floor(x * 100) / 100).toFixed(2);
      } else {
        var f = Math.round(x * 100) / 100;
        var s = f.toString();
        var rs = s.indexOf(".");
        if (rs < 0) {
          rs = s.length;
          s += ".";
        }
        while (s.length <= rs + 2) {
          s += "0";
        }
        if (s != "NaN.00") {
          this.form.emulateStep = s;
        } else {
          this.form.emulateStep = "";
        }
      }
    },
    //重新上传
    reUpload() {
      const temp = this.form.schemeId;
      this.resetScheme();
      this.form.schemeId = temp;
      // 表单隐藏
      this.showState = false;
      this.$nextTick(() => {
        this.$refs.upload.handleDelete(0);
      });
    },
  },
  watch: {
    // "form.schemeName"(value) {
    //   if (value == undefined || value == null || value == "") {
    //     if (
    //       this.form.schemeId == undefined ||
    //       this.form.schemeId == null ||
    //       this.form.schemeId == ""
    //     ) {
    //     }
    //     this.showState = false;
    //   } else {
    //     this.showState = true;
    //   }
    // },
  },
};
</script>
<style scoped>
/**时间插件宽度修改 */
.el-datetime-width >>> .el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}
</style>
